package util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import models.ClientApiAccess;
import models.GCalendarToken;
import models.YouUser;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.JsonNode;

import play.Play;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.WS;
import play.libs.WS.Response;

public class OAuthUtil {
	// 

	/**
	 * 1. Token Request (response_type=code)  <=== getCalendarTokenRequestUrl
	 * 2. User login and consent
	 * 3. Receive code
	 * 4. Exchange Code For Token
	 * 5. Token response
	 * 
	 * 
	 * see https://developers.google.com/accounts/docs/OAuth2#webserver
	 * @param youId
	 * @param clientApiAccess
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getGoogleTokenRequestUrl(long youId, String callback, ClientApiAccess clientApiAccess) {
		try {
			
			StringBuffer sb = new StringBuffer();
			sb.append(clientApiAccess.getAuthURL());
			sb.append('?');
			sb.append("response_type=code");
			sb.append("&client_id=");
			sb.append(URLEncoder.encode(clientApiAccess.getClientId(), "UTF-8"));
			sb.append("&redirect_uri=");
			sb.append(URLEncoder.encode(clientApiAccess.getRedirect(), "UTF-8"));
			sb.append("&scope=");
			sb.append(URLEncoder.encode(clientApiAccess.getScope(),"UTF-8"));
			sb.append("&state="); 
			sb.append(URLEncoder.encode(youId + (callback!=null? "$$" + callback : "") ,"UTF-8"));
			sb.append("&access_type=offline");
			sb.append("&approval_prompt=force");
			return sb.toString();
			
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}


	public static Promise<Response> revokeToken(String token) {
		String endpoint = Play.application().configuration()
				.getString("google.api.endpoint.revoke");
		
		return WS.url(endpoint).setQueryParameter("token", token).get();
	}

	public static JsonNode decodeBase64Json(String encodedIdToken) {
		try {
			byte[] decoded = Base64.decodeBase64(encodedIdToken.getBytes("UTF8"));
			String decodedIdToken = new String(decoded, "UTF8");
//			String decodedIdToken = new String(decoded).trim();
			System.out.println(decodedIdToken);
			JsonNode idTokenPayload = Json.parse(decodedIdToken);
			return idTokenPayload;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
